package org.dromara.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import org.dromara.app.appParams.AppDetailByIdParams;
import org.dromara.app.appParams.AppTuiJianParams;
import org.dromara.app.appReturn.AppMainstreamPartyReturn;
import org.dromara.app.cssUtils.CssUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.dromara.app.domain.bo.SkShopBo;
import org.dromara.app.domain.vo.SkShopVo;
import org.dromara.app.domain.SkShop;
import org.dromara.app.mapper.SkShopMapper;
import org.dromara.app.service.ISkShopService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 商家信息Service业务层处理
 *
 * @author Evacuation
 * @date 2024-07-23
 */
@RequiredArgsConstructor
@Service
public class SkShopServiceImpl implements ISkShopService {

    private final SkShopMapper baseMapper;

    /**
     * 查询商家信息
     *
     * @param id 主键
     * @return 商家信息
     */
    @Override
    public SkShopVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询商家信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 商家信息分页列表
     */
    @Override
    public TableDataInfo<SkShopVo> queryPageList(SkShopBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SkShop> lqw = buildQueryWrapper(bo);
        Page<SkShopVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的商家信息列表
     *
     * @param bo 查询条件
     * @return 商家信息列表
     */
    @Override
    public List<SkShopVo> queryList(SkShopBo bo) {
        LambdaQueryWrapper<SkShop> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SkShop> buildQueryWrapper(SkShopBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SkShop> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getCover()), SkShop::getCover, bo.getCover());
        lqw.eq(StringUtils.isNotBlank(bo.getBusinessHours()), SkShop::getBusinessHours, bo.getBusinessHours());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), SkShop::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getAddress()), SkShop::getAddress, bo.getAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getLongitude()), SkShop::getLongitude, bo.getLongitude());
        lqw.eq(StringUtils.isNotBlank(bo.getLatitude()), SkShop::getLatitude, bo.getLatitude());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), SkShop::getContent, bo.getContent());
        lqw.eq(StringUtils.isNotBlank(bo.getCity()), SkShop::getCity, bo.getCity());
        lqw.like(StringUtils.isNotBlank(bo.getTitle()), SkShop::getTitle, bo.getTitle());
        return lqw;
    }

    /**
     * 新增商家信息
     *
     * @param bo 商家信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SkShopBo bo) {
        SkShop add = MapstructUtils.convert(bo, SkShop.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改商家信息
     *
     * @param bo 商家信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SkShopBo bo) {
        SkShop update = MapstructUtils.convert(bo, SkShop.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SkShop entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除商家信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 尚科主流Party列表
     */
    @Override
    public List<AppMainstreamPartyReturn> getMainstreamParty(AppTuiJianParams params, HttpServletRequest req) {
        List<AppMainstreamPartyReturn> list = new ArrayList<>();
        List<SkShopVo> listAll = baseMapper.selectVoList(
            new QueryWrapper<SkShop>().lambda()
                .eq(StringUtils.isNotBlank(params.getCity()),SkShop::getCity, params.getCity())
                .eq(SkShop::getIsTj, 1)
                .orderByAsc(SkShop::getSort)
        );
        if (listAll.size() > 0) {
            list = BeanUtil.copyToList(listAll, AppMainstreamPartyReturn.class);
        }

        return list;
    }

    /**
     * 商家详情
     *
     * @param params
     * @param req
     * @return
     */
    @Override
    public AppMainstreamPartyReturn getShopInfo(AppDetailByIdParams params, HttpServletRequest req) {
        SkShop sk = baseMapper.selectById(params.getId());
        AppMainstreamPartyReturn app = BeanUtil.copyProperties(sk, AppMainstreamPartyReturn.class);
        //计算距离

        if(params.getLatitude()==null
            || params.getLatitude().isEmpty()
            || params.getLongitude()==null
            || params.getLongitude().isEmpty()
            || params.getLatitude().equals("")
            || params.getLongitude().equals("")
        ){
            return app;
        }
        if (params.getLatitude() != null && params.getLongitude() != null && app.getLatitude() != null && app.getLongitude() != null) {
            double juli = CssUtils.calculateDistance(Double.valueOf(params.getLatitude()),Double.valueOf(params.getLongitude()),Double.valueOf(app.getLatitude()),Double.valueOf(app.getLongitude()));
            app.setJuli(juli+"");
        }
        return app;
    }

    /**
     * 集市列表
     *
     * @param params
     * @param req
     * @return
     */
    @Override
    public List<AppMainstreamPartyReturn> getJiShiList(AppTuiJianParams params, HttpServletRequest req) {
        List<AppMainstreamPartyReturn> list = new ArrayList<>();
        List<SkShopVo> listAll = baseMapper.selectVoList(
            new QueryWrapper<SkShop>().lambda()
                .eq(StringUtils.isNotBlank(params.getCity()),SkShop::getCity, params.getCity())
                .like(StringUtils.isNotBlank(params.getSearCh()),SkShop::getTitle, params.getSearCh())
                .apply(StringUtils.isNotBlank(params.getProject()),
                    "JSON_CONTAINS(project, '\""+params.getProject()+"\"')")
                .orderByDesc(SkShop::getCreateTime)
        );
        if (listAll.size() > 0) {
            list = BeanUtil.copyToList(listAll, AppMainstreamPartyReturn.class);
        }
        if(params.getLatitude()==null
            || params.getLatitude().isEmpty()
            || params.getLongitude()==null
            || params.getLongitude().isEmpty()
            || params.getLatitude().equals("")
            || params.getLongitude().equals("")
        ){
            return list;
        }
        for(AppMainstreamPartyReturn vo:list){
            //计算距离
            if (params.getLatitude()!= null && params.getLongitude()!= null && vo.getLatitude()!= null && vo.getLongitude()!= null) {
                double juli = CssUtils.calculateDistance(Double.valueOf(params.getLatitude()),Double.valueOf(params.getLongitude()),Double.valueOf(vo.getLatitude()),Double.valueOf(vo.getLongitude()));
                String formattedDistance = String.format("%.2f", juli);
                double finalDistance = Double.parseDouble(formattedDistance);
                vo.setJuli(finalDistance+"");
            }
        }
        return list;
    }
}
